package com.jie.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author: 张玉捷
 * @Date: 2021/5/4 14:27
 */
@RestController
@RequestMapping("user")
public class userController {

    @Autowired //服务注册与发现客户端对象
    private DiscoveryClient discoveryClient;

    @Autowired //负载均衡客户端对象
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping
    public String invoke(){
        System.out.println("user demo ...");

        //1.调用订单服务，必须GET方式，接受返回String类型
//        RestTemplate restTemplate = new RestTemplate();
//        String orderResult = restTemplate.getForObject("http://"+randomHost()+"/order",String.class);

        //2.使用ribbon组件+restTemplate方式实现负载均衡 三种方式 discoveryClient,LoadBalanceClient,@LoadBalance
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("ORDERS");
//        serviceInstances.forEach(serviceInstance -> {
//            System.out.println("服务主机："+serviceInstance.getHost()+"服务端口："+serviceInstance.getPort()+"服务地址："+serviceInstance.getUri().toString());
//        });
//        String result = new RestTemplate().getForObject(serviceInstances.get(0).getUri()+"/order",String.class);


        //3.使用LoadBalanceClient进行服务调用
//        ServiceInstance serviceInstance = loadBalancerClient.choose("ORDERS");
//        System.out.println("服务主机："+serviceInstance.getHost()+"服务端口："+serviceInstance.getPort()+"服务地址："+serviceInstance.getUri().toString());
//        String result = restTemplate.getForObject(serviceInstance.getUri()+"/order",String.class);

        //4. 使用LoadBalance注解，作用：可以使对象具有ribbon负载均衡特性
        String result = restTemplate.getForObject("http://ORDERS/order",String.class);

        return "ok!!"+result;
    }

    //自定义随机策略
    public String randomHost(){
        List<String> hosts = new ArrayList<>();
        hosts.add("localhost:9999");
        hosts.add("localhost:9990");
        //生成随机数，再0-host.size()之间
        int i=new Random().nextInt(hosts.size());
        return hosts.get(i);
    }
}
